const db = wx.cloud.database()

var t = require("../../utils/module"),
  s = t(require("../../mainInfo.js"));

Page({


  data: {
    MAX_LIMIT: 20,
    page: 0,
    dataCount: 0,
    //热门搜索
    hotSearchItems: [],
    datas: [],
    searchTxt: "",
    logo: "",
    isSHow: false,
    isHasData: true,
    map: ["", 2, 3, 0, 1],
    city: "shanghai",
    ////////////////////////
    modalHidden: true,
    imgurl: "", //分类的图片
    clickitem: null, //分类的对象
    isfirst: true //是否第一次启动这个热词
  },


  onLoad: function(options) {
    this.data.dataCount = db.collection('product').count(),
      this.setData({
        config: s.default,
        map: this.data.map,
        city: wx.getStorageSync("city")
      })
    //热搜

    this.getHotItems().then(res => {
      console.log("【热搜项目】", res)
      var that = this;
      that.setData({
        //这个地方存的是个对象
        hotSearchItems: res.result.data
      })
    })

  },

  //获取热门搜索
  getHotItems: function() {
    var that = this;
    return new Promise(function(resolve, reject) {
      wx.cloud.callFunction({
        name: 'getHotItems',
        success: resolve,
        fail: reject
      })
    })
  },


  searchIcon: function(e) {
    this.data.searchTxt = e.detail.value
    this.data.datas = []
    this.data.page == 0
    this.onGetData()
  },
  onGetData: function() {
    this.data.page = 0;
    wx.showLoading({
      title: '正在加载数据中.....',
    })
    if (this.data.dataCount < this.data.page * this.data.MAX_LIMIT) {
      wx.showToast({
        title: '数据已经加载完',
        icon: "none"
      })
      wx.hideLoading()
      return
    }
    var that = this
    if (this.data.page == 0) {
      this.data.datas = []
    }
    var datas = db.collection('product').skip(this.data.page * this.data.MAX_LIMIT).limit(this.data.MAX_LIMIT).where({
      name: db.RegExp({
        regexp: that.data.searchTxt,
      })
    }).get({
      success: function(res) {
        wx.hideLoading()

        if (res.data.length == 0 && that.data.page == 0) {
          that.setData({
            isHasData: false
          })
        } else {
          that.data.page = that.data.page + 1
          for (var i = 0; i < res.data.length; i++) {
            that.data.datas.push(res.data[i])
          }
         
          that.setData({
            isfirst: false, //只有在第一次启动的时候显示热词
            datas: that.data.datas,
            isHasData: true
          })


          //批量更新云数据库
          //调用云函数
          
          console.log("----------" + that.data.searchTxt);
          wx.cloud.callFunction({
            name: 'allUpdateCount',
            data: {
              name: that.data.searchTxt,
            },
            success: res => {
              console.log("更新成功")
            }
          })
        }
      },
      fail: res => {
        wx.hideLoading()
        if (that.data.datas.length == 0) {
          that.setData({
            isHasData: false
          })
        }
        wx.showToast({
          title: '数据加载失败',
          icon: "none"
        })
      }
    })
  },
  onGoHome: function() {
    wx.switchTab({
      url: '/pages/ai/index',
    })
  },
  commit: function() {
    wx.navigateTo({
      url: '/pages/result/commit?keyword=' + this.data.searchTxt,
    })
  },
  /**
   * 显示弹窗
   */
  onBtnClick: function(event) {
    this.setData({
      modalHidden: false
    })
    var item = event.currentTarget.dataset.dat; //获取点击的这个对象
    var config = s.default
    var logoImg = config.cats[config.cities[this.data.city].cats[this.data.map[item.sortId]]].imageSrc
    var itemclass = config.cats[config.cities[this.data.city].cats[this.data.map[item.sortId]]].name
    this.setData({
      imgurl: logoImg,
      clickitem: item,
      itemclass: itemclass,

    })
  },


  /**
   * 点击取消
   */
  modalCandel: function() {
    // do something
    this.setData({
      modalHidden: true,
      isShow: this.data.isShow
    })
  },

  onItemClick: function(event) {
    var index = event.currentTarget.dataset.index
    var config = s.default
    var logoImg = config.cats[config.cities[this.data.city].cats[this.data.map[index]]].imageSrc
    this.setData({
      logo: logoImg,
      isShow: !this.data.isShow
    })
    //记录点击的这个，并且把  _count+1
    var item = event.currentTarget.dataset.data
    /**
     * 更新集合counters中的数据
     */

    var _count = item._count+1;   
    var _id=item._id;
    console.log("-------------_id:" + _id);
    console.log("-------------_count:" + _count);
    //调用云函数
    wx.cloud.callFunction({
      name: 'updateCount',
      data: {
        _id: _id,
        _count: _count
      },
      success: res => {
        console.log("更新成功")
      }
    })
  },
  hideModal: function() {
    this.setData({
      isShow: !this.data.isShow
    })
  },

  cancelSearch: function(t) {
    wx.navigateBack({
      delta: 1
    });
  },
  onPullDownRefresh: function() {
    this.data.page = 0
    this.data.datas = []
    this.onGetData()
  },

  onReachBottom: function() {
    this.onGetData()
  },

})